//
//  RegiterViewController.m
//  jiyujiaProgram
//
//  Created by 中良 赵 on 15/10/13.
//  Copyright (c) 2015年 中良 赵. All rights reserved.
//

#import "RegiterViewController.h"
#import <CoreLocation/CoreLocation.h>

#import "MemberModel.h"
#import "EaseMob.h"

@interface RegiterViewController () <CLLocationManagerDelegate,UIAlertViewDelegate,UITextFieldDelegate>

@end

@implementation RegiterViewController
{
    CLLocationManager *_locationManager;
    NSString *_lat;
    NSString *_lng;
    
    MemberModel *_model;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden=YES;
    [self creatLocationManager];
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(10, 20, 30, 30)];
    [btn setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(backaction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
}
-(void)backaction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [_locationManager startUpdatingLocation];
}

- (void)creatLocationManager
{
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        [_locationManager requestWhenInUseAuthorization];
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        [_locationManager requestWhenInUseAuthorization];
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        _locationManager.allowsBackgroundLocationUpdates = NO;
    }
}


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    for (CLLocation *userLocation in locations) {
        if (_lat.length <1 &&_lng.length < 1) {
            _lat = [NSString stringWithFormat:@"%f",userLocation.coordinate.latitude];
            _lng = [NSString stringWithFormat:@"%f",userLocation.coordinate.longitude];
        }else{
            [_locationManager stopUpdatingLocation];
        }
        NSLog(@"***CLLOCATION***%@***",userLocation);
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.securityTextField resignFirstResponder];
    [self.userTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sendSecurity:(id)sender
{
    [self.securityTextField resignFirstResponder];
    [self.userTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];


    NSDictionary *param = @{
                            @"mobile":_userTextField.text,
                            @"status":@"0",
                            };
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(CHECKCODE) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            if ([result[@"errCode"] integerValue] == 200) {
                SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
            }else{
                SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
            }
        }
    }];
}

- (IBAction)regiterClick:(id)sender
{
//    [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:self.userTextField.text password:self.userTextField.text withCompletion:^(NSString *username, NSString *password, EMError *error) {
//        if (!error) {
//            NSLog(@"注册成功,**%@**%@**",username,password);
//            SHOW_ALERT(@"提示", _model.errMsg, @"好的", nil, self);
////            [userInfo saveUserInfoToSanbox];
//        }else{
//            NSLog(@"环信注册失败%@",error);
//        }
//    } onQueue:nil];

    [self.securityTextField resignFirstResponder];
    [self.userTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];

    NSDictionary *param = @{
                            @"mobile":_userTextField.text,
                            @"password":_passwordTextField.text,
                            @"checkCode":_securityTextField.text,
                            @"diver_token":[[[UIDevice currentDevice] identifierForVendor] UUIDString],
                            @"member_type":[NSString stringWithFormat:@"%ld",_typeSegment.selectedSegmentIndex + 1],
                            @"lng":_lng,
                            @"lat":_lat,
                            };
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(RESIGN) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            _model = [[MemberModel alloc] init];
            _model = [MemberModel objectWithKeyValues:result];
            userInfo.memberModel = _model;
            userInfo.user = self.userTextField.text;
            userInfo.password = self.passwordTextField.text;
            if ([_model.errCode integerValue] == 200) {
                [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:self.userTextField.text password:self.userTextField.text withCompletion:^(NSString *username, NSString *password, EMError *error) {
                    if (!error) {
                        NSLog(@"注册成功,**%@**%@**",username,password);
                        SHOW_ALERT(@"提示", _model.errMsg, @"好的", nil, self);
                        [userInfo saveUserInfoToSanbox];
                    }else{
                        NSLog(@"环信注册失败%@",error);
                    }
                } onQueue:nil];
            }else{
                SHOW_ALERT(@"提示", _model.errMsg, @"好的", nil, nil);
            }
        }
    }];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
